#!/usr/bin/env python

import sys
import string
import urllib2
import email.MIMEText
import smtplib
import os
import os.path
import glob


def cookie_filename():
    path = os.path.join(os.environ['USERPROFILE'], 'Cookies')
    for file in  os.listdir(path):
        if file.find('dailygammon') != -1:
            return os.path.join(path, file)

def read_cookie(data):
    values = []
    line = data.readline()
    while line:
        key = string.strip(line)
        line = data.readline()
        values.append(key + '=' + string.strip(line))
        while line and string.strip(line) != '*':
            line = data.readline()
        line = data.readline()
    return string.join(values, '; ')


def main(args=None):
    if args == None:
        args = sys.argv

    the_url = 'http://www.dailygammon.com/bg/top'

    mailhost = 'wlooevs1.aqua.mitra.com'
    from_address = os.environ['USERNAME'];
    to_addresses = [from_address]
    subject = 'Time to play Backgammon'

    r = urllib2.Request(url=the_url)
    r.add_header('Cookie', read_cookie(file(cookie_filename())))

    f = urllib2.urlopen(r)

    page = ''
    for line in f.readlines():
        if line.find('no matches') != -1:
            return 0
        elif  line.find('/HEAD') != -1:
            page = page + '<BASE href="' + the_url + '">\r\n'
        
        page = page + line

    # Send the mail
    msg = email.MIMEText.MIMEText(page, 'html')
    msg['Subject'] = subject
    msg['To'] = string.join(to_addresses, ', ')
    
    s = smtplib.SMTP(mailhost)
    s.sendmail(from_address, to_addresses, msg.as_string())
    s.close()

    return 0


if __name__ == '__main__':
    sys.exit(main())

